package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.User;
import exception.LoginException;
import service.UserService;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取用户名和密码
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		//调用userservice判断用户名和密码是否正确
		UserService service =new UserService();
		try {
			User user= service.lonin(username,password);
			if(user.getState()==1) {//用户状态为激活
				request.getSession().setAttribute("user",user);
				//用户为超级用户
				String role=user.getRole();
				if(role.equals("超级用户")) {
					response.sendRedirect(request.getContextPath()+"/admin/login/home.jsp");
					return;
				}else {
					response.sendRedirect(request.getContextPath()+"/client/myAccount.jsp");
					return;
				}
			}
			
		} catch (LoginException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("login_message", e.getMessage());
			request.getRequestDispatcher("/client/login.jsp").forward(request, response);
			return;
		}
		
}
}